﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading.Tasks;

namespace Dashboard
{


    public class iToolLoggerSaveProvider
    {
        private readonly Subject<iToolLoggerModel> subject;
        private readonly iToolLoggerConfiguration iToolLoggerConfiguration;
        static object _writeLock = new object();

        public iToolLoggerSaveProvider(iToolLoggerConfiguration config)
        {
            this.iToolLoggerConfiguration = config;

            if (!Directory.Exists(config.LogPath + "/" + LogLevel.Debug))
                Directory.CreateDirectory(config.LogPath + "/" + LogLevel.Debug);
            if (!Directory.Exists(config.LogPath + "/" + LogLevel.Trace))
                Directory.CreateDirectory(config.LogPath + "/" + LogLevel.Trace);
            if (!Directory.Exists(config.LogPath + "/" + LogLevel.Critical))
                Directory.CreateDirectory(config.LogPath + "/" + LogLevel.Critical);
            if (!Directory.Exists(config.LogPath + "/" + LogLevel.Warning))
                Directory.CreateDirectory(config.LogPath + "/" + LogLevel.Warning);
            if (!Directory.Exists(config.LogPath + "/" + LogLevel.Information))
                Directory.CreateDirectory(config.LogPath + "/" + LogLevel.Information);
            if (!Directory.Exists(config.LogPath + "/" + LogLevel.Error))
                Directory.CreateDirectory(config.LogPath + "/" + LogLevel.Error);

            this.subject = new Subject<iToolLoggerModel>();
            this.subject
                .Buffer(TimeSpan.FromSeconds(5), 100)
                .Where(x => x.Count > 0)
                .Select(list => Observable.FromAsync(() => BatchInsertData(list)))
                .Concat()
                .Subscribe();

        }

        public void InsertItem(iToolLoggerModel log)
        {
            this.subject.OnNext(log);
        }

        private Task BatchInsertData(IList<iToolLoggerModel> list)
        {
            string filePath = iToolLoggerConfiguration.LogPath + $"/{DateTime.Now.ToString("yyyyMMdd")}" + iToolLoggerConfiguration.LogName;

            lock (_writeLock)
            {

                using (StreamWriter stream = new StreamWriter(filePath, true, Encoding.Default))
                {
                    foreach (var item in list)
                    {
                        stream.WriteLine("#### " + item.Level + "\t" + DateTime.Now.ToString() + "\t`" + item.CategoryName + "`\n``` json\n" + item.Message + "\n```");
                    }

                    stream.Flush();
                    stream.Close();
                }
            }

            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// ILogger
    /// </summary>
    public class iToolLogger : ILogger, IDisposable
    {
        public string categoryName;
        private readonly iToolLoggerSaveProvider saveProvider;
        private readonly iToolLoggerConfiguration iToolLoggerConfiguration;

        public iToolLogger(string categoryName, iToolLoggerConfiguration config)
        {
            this.saveProvider = new iToolLoggerSaveProvider(config);
            this.categoryName = categoryName;
            this.iToolLoggerConfiguration = config;
        }

        public IDisposable BeginScope<TState>(TState state) => this;

        public void Dispose() { }

        public bool IsEnabled(LogLevel logLevel) => this.iToolLoggerConfiguration.MinLevel <= logLevel;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (this.IsEnabled(logLevel))
            {
                this.saveProvider.InsertItem(new iToolLoggerModel
                {
                    Level = logLevel,
                    CategoryName = categoryName,
                    Message = formatter(state, exception)
                });
            }
        }

    }

    /// <summary>
    /// ILoggerProvider
    /// </summary>
    public class iToolFileLoggerProvider : ILoggerProvider
    {

        private readonly iToolLoggerConfiguration _config;

        public iToolFileLoggerProvider(iToolLoggerConfiguration config = null)
        {
            this._config = config ?? new iToolLoggerConfiguration();
        }

        public ILogger CreateLogger(string categoryName)
        {
            return new iToolLogger(categoryName, _config);
        }

        public void Dispose()
        {

        }
    }

    public class iToolLoggerConfiguration
    {
        public iToolLoggerConfiguration()
        {
            MinLevel = LogLevel.Debug;
        }
        public LogLevel MinLevel { get; set; }
        public string LogPath { get; set; } = AppDomain.CurrentDomain.BaseDirectory + "/logs";
        public string LogName { get; set; } = "log.md";
    }

    public class iToolLoggerModel
    {
        public string CategoryName { get; set; }
        public LogLevel Level { get; set; }
        public string Message { get; set; }
    }


}
